import adminService from '@/service/adminService'
import {getToken, getUserId, removeToken, removeUserId, setToken, setUserId, setRoleId, getRoleId, removeRoleId, getUserName, setUserName, removeUserName, getActive, removeActive, setActive} from '@/utils/auth'
import i18n from '@/lang'

const user = {
  state: {
    token: getToken() || null,
    userid: (getUserId() && JSON.parse(getUserId())) || null,
    username: '',
    userStat: Number(getRoleId()) || null,
    active: getActive() || null
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USERID: (state, userid) => {
      state.userid = userid
      setUserId(userid)
    },
    SET_USERNAME: (state, username) => {
      state.username = username
      // sessionStorage.setItem('truename', username)
    },
    SET_USERSTAT: (state, userStat) => {
      state.userStat = userStat
    },
    SET_ACTIVE: (state, active) => {
      state.active = active
      setActive(active)
    }
  },

  actions: {
    setActive({commit}, active) {
      commit('SET_ACTIVE', active)
    },
    /**
     * 登录
     */
    doLogin ({commit}, userInfo) {
      return new Promise((resolve, reject) => {
        adminService.loginByLoginname(userInfo).then(response => {
          const data = response.data
          if (data.result === 0) {
            commit('SET_TOKEN', data.data.token)
            setToken(data.data.token)
            commit('SET_USERID', data.data.userid)
            setUserId(data.data.userid)
            commit('SET_USERNAME', data.data.loginname)
            setUserName(data.data.loginname)
            commit('SET_USERSTAT', data.data.roleid)
            setRoleId(data.data.roleid)
            resolve(i18n.t('login.SUCCESS'))
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    /**
     * 登出
     */
    LogOut ({commit}, userInfo) {
      return new Promise((resolve, reject) => {
        adminService.logout(userInfo).then(response => {
          commit('SET_TOKEN', '')
          commit('SET_USERID', '')
          commit('SET_USERSTAT', '')
          commit('SET_USERNAME', '')
          removeRoleId()
          removeToken()
          removeUserId()
          removeUserName()
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    /**
     * cookie 超时退出
     */
    OuttimeLogOut({commit}, userInfo) {
      commit('SET_TOKEN', '')
      commit('SET_USERID', '')
      commit('SET_USERSTAT', '')
      commit('SET_USERNAME', '')
      removeRoleId()
      removeToken()
      removeUserId()
      removeUserName()
    }

  }

}

export default user
